/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.jennic.internal;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.gateway.jennic.IMessageHandler;
import org.osami.gateway.jennic.IMessageSource;
import org.osami.gateway.jennic.Message;
import org.osami.gateway.jennic.internal.multicast.MulticastInboundMessage;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 26 mai 2010
 * Time: 15:45:08
 * To change this template use File | Settings | File Templates.
 */
@Component
@Provides(specifications = IMessageSource.class)
public class JennicMessageReceiver implements Runnable, IMessageSource {

    @ServiceProperty
    private String hostname;

    @ServiceProperty
    private int port;

    @ServiceProperty
    private String type;

    private DatagramSocket socket;
    private static final int MAX_SIZE = 1402; // ??

    private List<IMessageHandler> handlers;

    private Thread thread;

    public JennicMessageReceiver() {
        this.handlers = new ArrayList<IMessageHandler>();
    }

    @Validate
    public void start() throws Exception {
        InetAddress address = InetAddress.getByName(hostname);
        System.out.println("InetAddress " + hostname + " -> " + address);
        socket = new DatagramSocket(port, address);

        System.out.println("Bound InetAddress " + socket.getLocalAddress());
        thread = new Thread(this);
        thread.start();

    }

    @Invalidate
    public void stop() {
        socket.close();
    }


    public void run() {
            System.out.println("Thread.run() !!!");

        byte[] buffer = new byte[MAX_SIZE];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (!socket.isClosed()) {
            System.out.println("Waiting for next packet on port " + port + "...");

            try {
                socket.receive(packet);
                parsePacket(packet);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    private void parsePacket(DatagramPacket packet) throws Exception {

        int length = packet.getLength();
        int offset = packet.getOffset();
        byte[] buffer = packet.getData();

        String message = new String(buffer, offset, length);
        MulticastInboundMessage msg = new MulticastInboundMessage(message);
        fireNewMessage(msg);
    }

    public void registerHandler(IMessageHandler handler) {
        System.out.println("Registering handler: " + handler);
        synchronized(handlers) {
            this.handlers.add(handler);
        }
    }

    public void unregisterHandler(IMessageHandler handler) {
        System.out.println("Unregistering handler: " + handler);
        synchronized(handlers) {
            this.handlers.remove(handler);
        }
    }

    public void fireNewMessage(Message message) {
        System.out.println("Received message : " + message);
        synchronized(handlers) {
            for (IMessageHandler handler : handlers) {
                handler.handle(message);
            }
        }
    }
}
